package com.jiajia.study.netty.chapter01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.StandardCharsets;

public class MyNettyServer {
    public static void main(String[] args) {
        // 服务端启动
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //
        serverBootstrap.channel(NioServerSocketChannel.class);

        // 创建一组线程，通过死循环，监控状态：ACCEPT  READ  WRITE
        serverBootstrap.group(new NioEventLoopGroup());

        // 去监听 ： accept read write 事件，做相应的逻辑处理
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
//                内置的解码器
//                ch.pipeline().addLast(new StringDecoder()) ;
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                    /*
                        我们通过自己拿到 ByteBuf 自己去解析数据
                     */
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf byteBuf = (ByteBuf) msg;
                        String result = ((ByteBuf)msg).toString(StandardCharsets.UTF_8);
                        System.out.println("the result is : " +result);
                    }
                });
            }
        });

        // 绑定 9999 端口
        serverBootstrap.bind(9999);

    }
}
